package it.polimi.swKnights.SWIMv2.servlets;

import it.polimi.swKnights.SWIMv2.ejb.abilityManager.AbilityHandlerRemote;
import it.polimi.swKnights.SWIMv2.general.PersistenceManagerUtility;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * Basic class for all SWIMv2 Servlets. Extends the HttpServlet base class.
 * Includes some convenience methods useful for all servlets of this project
 */
abstract public class SwimServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * Enterprise JavaBean lookup wrapper
	 * 
	 * @param <T>
	 * 
	 * @param clazz
	 *            the remote interface of the requested bean. The interface must
	 *            be named ${beanName}Remote in order to collect the correct
	 *            bean
	 */
	protected <T> T lookUp(Class<T> clazz)
	{
		return PersistenceManagerUtility.lookUp(clazz);
	}

	protected Boolean getTruthFromRadio(String value)
	{
		if (value.equalsIgnoreCase("Approve"))
			return true;
		else
			return false;
	}

	protected boolean getDirect(HttpServletRequest request)
	{
		String directString = request.getParameter("direct");
		if (directString == null)
			return false;
		else
			return Boolean.parseBoolean(directString);
	}

	protected List<Map<String, String>> getList(Object o)
	{
		List<Map<String, String>> listOfMap = new  ArrayList<Map<String,String>>();
		
		List<?> list = (List<?>) o;
		for(Object item : list)
		{
			if(item instanceof Map<?,?>)
			{
				Map<?,?> map = (Map<?,?>) item;
				Map<String, String> mapUserLoop = this.getMap(map);
				listOfMap.add(mapUserLoop);
			}
		}
		
		return listOfMap;
	}

	private Map<String, String> getMap(Map<?,?> map)
	{
		Map<String, String> stringMap = new HashMap<String, String>();
		for(Entry<?,?> entry : map.entrySet())
		{
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			stringMap.put(key, value);
		}
		
		return stringMap;
	}
	
	protected Map<String, String> getUserAbilities(String username) 
	{
		AbilityHandlerRemote abilityManager = this.lookUp(AbilityHandlerRemote.class);
		
		
		Map<String, String> abilities = abilityManager.getUserabilities(username);
		return abilities;
		
	}
	

}
